package wait

import (
	"log"
	"time"

	"smartconn.cc/tosone/parsing/model"
)

var modeBool bool
var channel chan bool

func init() {
	modeBool = false
}

// Index 等待模式的入口
func Index(res model.RegexResult, options model.ModelsOptions) model.ModeResponse {
	modeBool = true
	channel = make(chan bool, 1)
	go func() {
		t, _ := time.ParseDuration(res.Time + "ms")
		time.Sleep(t)
		channel <- true
		defer func() {
			if r := recover(); r != nil {
				log.Println("handler/wait: Cannot write something to close channel.")
				return
			}
		}()
	}()
	<-channel
	response := model.ModeResponse{Sound: []string{}, Backline: 1}
	return response
}

// Stop 等待模式的结束
func Stop() {
	if modeBool {
		modeBool = false
		close(channel)
	}
}
